#!/bin/bash

DATE=`date +"%y_%m_%d_%H_%M_%S"`
TMP_FILE=/tmp/test_cnf_${DATE}_${RANDOM}

FILE=$1

OUTPUT=`echo $FILE | sed s/".cnf"/"_without_unary.cnf"/g`

if [[ "$#" != 1 ]]
then
        echo "Wrong number of parameters. Expected 1." >&2
        exit 1
fi

if ! [[ -e "$FILE" ]]
then
        echo "Could not find the CNF file." >&2
        exit 1
fi

if [[ -e "$OUTPUT" ]]
then
        echo "Output file already exists." >&2
        exit 1
fi


rm $TMP_FILE 2> /dev/null

TOTAL_CLAUSES=0

while read line
do

	if [[ $line =~ ^"p cnf "[0-9]+" "[0-9]+ ]]
	then
		NEXT_VARIABLE=`echo $line | cut -d " " -f 3`
		let NEXT_VARIABLE++
	fi

	if [[ $line =~ ^"c".* ]]
	then
		echo "$line" >> $TMP_FILE
	fi

	if [[ $line =~ ^" "*("-"?[0-9]+" "+)+"0"" "* ]]
	then
		CLAUSE=($line)
                VARS=`echo ${#CLAUSE[@]} `
                let VARS--

                if [[ $VARS == "1" ]]
                then
                        NEW_VAR_1=$NEXT_VARIABLE
                        let NEXT_VARIABLE++

                        echo $NEW_VAR_1 ${CLAUSE[0]}" 0" >> $TMP_FILE
                        echo "-"$NEW_VAR_1 ${CLAUSE[0]}" 0" >> $TMP_FILE
                        let TOTAL_CLAUSES+=2

		else
			echo $line >> $TMP_FILE
			let TOTAL_CLAUSES++
                fi
	fi

done < $FILE

let NUMBER_OF_VARIABLES=${NEXT_VARIABLE}-1

echo "p cnf $NUMBER_OF_VARIABLES $TOTAL_CLAUSES" > $OUTPUT
cat $TMP_FILE >> $OUTPUT

rm $TMP_FILE
